package com.cmhi.softmbh.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DevInfoManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chinamobile.SWDevInfoManager;
import com.cmhi.base.activity.HiddenActivity;
import com.cmhi.softmbh.BuildConfig;
import com.cmhi.softmbh.R;
import com.cmhi.softmbh.entity.Entity;
import com.cmhi.softmbh.provider.DBUtil;
import com.cmhi.softmbh.util.BitmapUtil;
import com.cmhi.softmbh.util.HardwareUtil;
import com.cmhi.softmbh.util.ToastUtils;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.MacUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;


public class SettingsActivity extends Activity implements Handler.Callback {

    private String reSetPwd = "cmcc86";
    private Handler handler;
    //二维码
//    private Bitmap bitmap;
    //二维码提示信息：云化机顶盒
//    private TextView qrCodeTextView;
    //二维码图片
//    private ImageView qrCodeImageView;
    private Stack<Integer> keyObserve;
    private List<Integer> keyOrder = Arrays.asList(KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_RIGHT,
            KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_DOWN,
            KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_UP);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        AppUtils.debugLog("SettingsActivity-->onCreate");
        setContentView(R.layout.activity_setting);
        handler = new Handler(this);
        keyObserve = new Stack<>();
        keyObserve.addAll(keyOrder);
        Button userReset = findViewById(R.id.user_reset);
        findViewById(R.id.app_reset).setVisibility(View.GONE);

        findViewById(R.id.llFinish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        userReset.setOnClickListener(view -> {//用户重置按钮
            final AlertDialog dialog = new AlertDialog.Builder(this, R.style.style_alert_confirm_dialog).create();
            dialog.show();
            dialog.setCancelable(true);
//                    FLAG_ALT_FOCUSABLE_IM
            dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            dialog.getWindow().setContentView(R.layout.alert_input_dialog);

            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
            //设置dialog弹窗宽高
            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
            dialog.getWindow().setGravity(Gravity.CENTER);
            //调整明暗度，float值，完全透明不变暗是0.0f，完全变暗不透明是1.0f
            params.dimAmount = 0.3f;
            dialog.getWindow().setAttributes(params);


            Button btnPositive = (Button) dialog.findViewById(R.id.alertdialogconfirm_confirm);
            Button btnNegative = (Button) dialog.findViewById(R.id.alertdialogconfirm_cancel);
            final EditText etPwd = (EditText) dialog.findViewById(R.id.et_pwd);
            //适配当贝键盘无法弹出的问题
            etPwd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (v == etPwd) {
                        if (hasFocus) {
                            HardwareUtil.showSoftKeyBoard(etPwd, SettingsActivity.this);
                        }
                    }
                }
            });
            btnPositive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    String str = etPwd.getText().toString().trim();
                    if (TextUtils.isEmpty(str)) {
                        ToastUtils.show("请输入重置密码...");
                    } else {
                        if (str.equals(reSetPwd)) {
                            dialog.dismiss();
                            setZwData(DevInfoManager.LAUNCHER, "com.chinamobile.activate");
                            setZwData(DevInfoManager.PHONE, "");
                            setZwData(DevInfoManager.ACCOUNT, "");
                            DBUtil.delete(Entity.FROM_BAI_DU_ACCOUNT);
                            DBUtil.delete(Entity.ACCOUNT);
                            DBUtil.delete(Entity.LICENSE_CODE);
                            DBUtil.delete(Entity.ACTIVATED_NEW_TV);
                            DBUtil.update(Entity.RESET, Entity.TRUE);
                            Intent intent = getPackageManager().getLaunchIntentForPackage(BuildConfig.APPLICATION_ID);
                            if (intent != null) {
                                startActivity(intent);
                            }
                            finish();
                        } else {
                            ToastUtils.show("密码不正确，请重新输入");
                        }
                    }
                }
            });
            btnNegative.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    dialog.dismiss();
                }
            });
        });
//        qrCodeTextView = findViewById(R.id.qr_code_tip);
//        qrCodeImageView = findViewById(R.id.qr_code_image);
        //芯片型号
        String cpuModel = HardwareUtil.getCpuModel();
        ((TextView) findViewById(R.id.cpu_model)).setText(cpuModel);
        //芯片核心数
        int cpuCores = HardwareUtil.getCpuCoreNumber();
        //芯片频率
        String cpuFrequency = HardwareUtil.getCpuFrequencyStr();
        if (cpuFrequency.equals("0.00")) {
            findViewById(R.id.tv_cpu_num).setVisibility(View.GONE);
            findViewById(R.id.cpu_parameters).setVisibility(View.GONE);
        } else {
            //芯片参数
            ((TextView) findViewById(R.id.cpu_parameters)).setText(cpuCores + " 核  " + cpuFrequency + " GHz");
        }
        //安卓版本
        ((TextView) findViewById(R.id.android_version)).setText(Build.VERSION.RELEASE + " (" + Build.VERSION.SDK_INT + ")");
        //设备型号
        String model = Build.MODEL;
        ((TextView) findViewById(R.id.model)).setText(model);
        //设备厂商
        String brand = DBUtil.query(Entity.BRAND);
        ((TextView) findViewById(R.id.brand)).setText(brand);
        //总存储空间
        String totalRom = HardwareUtil.getTotalRomStr();
        //存储空间
        ((TextView) findViewById(R.id.rom)).setText(HardwareUtil.getAvailableRomStr() + "/" + totalRom);
        //总内存大小
        String totalRam = HardwareUtil.getTotalMemory() + " MB";
        //内存大小
        ((TextView) findViewById(R.id.ram)).setText(HardwareUtil.getAvailableMemoryStr() + "/" + totalRam);
        //软件版本
        String app_version = "V" + BuildConfig.VERSION_NAME;
        ((TextView) findViewById(R.id.app_version)).setText(app_version);
        //STBID 终端唯一标识
        String stbid = DBUtil.query(Entity.VIRTUAL_STBID);
        ((TextView) findViewById(R.id.stbid)).setText(stbid);
        if (!stbid.isEmpty()) {
            ((ImageView) findViewById(R.id.bar_code_image)).setImageBitmap(BitmapUtil.generateBarBitmap(stbid, 800, 100));
        }
        //虚拟 MAC 地址
        String mac = DBUtil.query(Entity.VIRTUAL_MAC);
        //虚拟 MAC 地址加冒号
        String macAddColon = "";
        if (mac.length() == 12) {
            macAddColon = mac.substring(0, 2) + ":" + mac.substring(2, 4) + ":" + mac.substring(4, 6) + ":" +
                    mac.substring(6, 8) + ":" + mac.substring(8, 10) + ":" + mac.substring(10, 12);
        }
        ((TextView) findViewById(R.id.mac)).setText(macAddColon);
        //IP 地址
        String ip = HardwareUtil.getLocalIpAddress();
        ((TextView) findViewById(R.id.ip)).setText(ip);
        //业务账号
        String account = DBUtil.query(Entity.ACCOUNT);
        ((TextView) findViewById(R.id.account)).setText(account);
        //所在省份
        ((TextView) findViewById(R.id.province)).setText("江苏");
        if (!account.isEmpty()) {
            //终端厂商
            String manufacturer = DBUtil.query(Entity.MANUFACTURER);
            //终端型号
            String modelName = DBUtil.query(Entity.MODEL_NAME);
            //一级平台授权码
            String appToken = DBUtil.query(Entity.APP_TOKEN);
            String contents = "";

            try {
                contents = "https://softmbh.komect.com/reward/index.html?" +
                        "SDK=" + Build.VERSION.SDK_INT +
                        "&TVManufacturer=" + URLEncoder.encode(brand, "UTF-8") +
                        "&model=" + model +
                        "&cpu=" + cpuModel +
                        "&cpuInfo=" + cpuCores + URLEncoder.encode("核", "UTF-8") + cpuFrequency + "GHz" +
                        "&systemTotalMemorySize=" + totalRam +
                        "&SDTotalSize=" + totalRom +
                        "&Manufacturer=" + manufacturer +
                        "&ModelName=" + modelName +
                        "&mac=" + mac +
                        "&STBID=" + stbid +
                        "&MobilePhoneNumber=" + account +
                        "&Account=" + account +
                        "&ip=" + ip +
                        "&version=" + app_version +
                        "&city=" + URLEncoder.encode("江苏省", "UTF-8") +
                        "&provinceCode=320000" +
                        "&tvmac=" + MacUtils.getMac() +
                        "&baseinfo=" + DBUtil.query(Entity.BASE_INFO)+
                        "&appToken=" + appToken;
                contents = contents.replace(" ", "");
                AppUtils.debugLog("QR_code contents : " + contents);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
//            AppUtils.debugLog("Density : " + displayMetrics.density + ", densityDpi : " + displayMetrics.densityDpi +
//                    ", width : " + displayMetrics.widthPixels + ", height : " + displayMetrics.heightPixels);
//            if (displayMetrics.densityDpi == 213) {
//                //小米和海信电视的宽高设置为230时会很小，231会稍大，小于230一样效果，大于231一样效果
//                bitmap = BitmapUtil.generateQRCode(contents, 231, 231);
//            } else {
//                bitmap = BitmapUtil.generateQRCode(contents, 300, 300);
//            }
            handler.sendEmptyMessage(1);
        }
    }


    //写入卓望数据
    private void setZwData(String key, String value) {
        SWDevInfoManager.getInstance(this.getApplicationContext())
                .update(key,
                        value,
                        DevInfoManager.Default_Attribute,
                        result -> {// 0 成功，否则失败
                            AppUtils.debugLog(key + " : " + value + " : " + (result == 0 ? "success" : result));
                        });
    }

    @Override
    public boolean handleMessage(Message message) {
        if (message.what == 1) {//显示二维码
//            qrCodeImageView.setImageBitmap(bitmap);
//            qrCodeImageView.setVisibility(View.VISIBLE);
//            qrCodeTextView.setVisibility(View.GONE);
        } else if (message.what == 2) {
            if (keyObserve.size() != keyOrder.size()) {
                //恢复健值监听
                keyObserve.clear();
                keyObserve.addAll(keyOrder);
            }
        }
        return false;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            int temp = keyObserve.peek();
            if (temp == event.getKeyCode()) {
                keyObserve.pop();
                if (keyObserve.size() == 0) {//用户全部按完了预定按键
                    if (handler.hasMessages(2)) {
                        handler.removeMessages(2);
                    }
                    //恢复健值监听
                    keyObserve.addAll(keyOrder);
                    startActivity(new Intent(this, HiddenActivity.class));
                } else {
                    //做一个延时，延时两秒恢复按键状态
                    if (handler.hasMessages(2)) {
                        handler.removeMessages(2);
                    }
                    handler.sendEmptyMessageDelayed(2, 2000);
                }
            } else if (keyObserve.size() != keyOrder.size()) {
                //恢复健值监听
                keyObserve.clear();
                keyObserve.addAll(keyOrder);
            }
        }
        return super.dispatchKeyEvent(event);
    }
    @Override
    protected void onDestroy() {
        AppUtils.debugLog("onDestroy");
        ToastUtils.cancel();
        //清空消息，预防内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }
}
